const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const request = (url, params, success, fail, compl) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  params['openId'] = wx.getStorageSync("openId");
  wx.request({
    url: url,
    data: params,
    success: function (res) {
      wx.hideLoading();
      if (res.data.status == 200) {
        success(res.data);
      } else {
        wx.showToast({
          title: String(res.data.msg),
          icon: 'none'
        })
        fail(res.data);
      }
    },
    fail: function () {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      fail(null);
    },
    complete: function() {
      compl();
    }
  })
}

const accMul = (arg1, arg2) => {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try { m += s1.split(".")[1].length } catch (e) { };
  try { m += s2.split(".")[1].length } catch (e) { };
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

const accDiv = (arg1, arg2) => {
  var t1 = 0,
    t2 = 0,
    r1, r2;
  try { t1 = arg1.toString().split(".")[1].length; } catch (e) { }
  try { t2 = arg2.toString().split(".")[1].length; } catch (e) { }
  // with (Math) {
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  // }
}

module.exports = {
  formatTime: formatTime,
  request: request,
  accMul: accMul,
  accDiv: accDiv
}
